import { randomBytes } from 'crypto';

export interface CaptchaResult {
  uuid: string;
  image: string;
  text: string;
  captchaEnabled: boolean;
}
/**
 * 暂时不用
 * 验证码工具类
 */
export class CaptchaUtil {
  private static captchaStore = new Map<
    string,
    { text: string; expires: number }
  >();

  /**
   * 生成验证码（简化版，返回SVG图像）
   */
  static generateCaptcha(length: number = 4): CaptchaResult {
    const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    let text = '';
    for (let i = 0; i < length; i++) {
      text += chars.charAt(Math.floor(Math.random() * chars.length));
    }

    const uuid = randomBytes(16).toString('hex');

    // 存储验证码，5分钟过期
    this.captchaStore.set(uuid, {
      text,
      expires: Date.now() + 5 * 60 * 1000,
    });

    // 生成SVG验证码图像
    const width = 120;
    const height = 40;
    let svg = `<svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">`;
    svg += '<rect width="100%" height="100%" fill="#f0f0f0"/>';

    // 绘制文字
    for (let i = 0; i < text.length; i++) {
      const x = (width / (text.length + 1)) * (i + 1);
      const y = height / 2 + (Math.random() - 0.5) * 10;
      const angle = (Math.random() - 0.5) * 20;
      const color = `hsl(${Math.random() * 60 + 200}, 70%, 50%)`;

      svg += `<text x="${x}" y="${y}" font-family="Arial" font-size="20" fill="${color}" text-anchor="middle" transform="rotate(${angle} ${x} ${y})">${text[i]}</text>`;
    }

    // 添加干扰线
    for (let i = 0; i < 3; i++) {
      const x1 = Math.random() * width;
      const y1 = Math.random() * height;
      const x2 = Math.random() * width;
      const y2 = Math.random() * height;
      const color = `hsl(${Math.random() * 360}, 50%, 70%)`;
      svg += `<line x1="${x1}" y1="${y1}" x2="${x2}" y2="${y2}" stroke="${color}" stroke-width="1" opacity="0.5"/>`;
    }

    svg += '</svg>';

    // 转换为base64
    const image = `data:image/svg+xml;base64,${Buffer.from(svg).toString('base64')}`;

    return {
      uuid,
      image,
      text,
      captchaEnabled: true,
    };
  }

  /**
   * 验证验证码
   */
  static verifyCaptcha(uuid: string, inputText: string): boolean {
    const captcha = this.captchaStore.get(uuid);

    if (!captcha) {
      return false;
    }

    // 检查是否过期
    if (Date.now() > captcha.expires) {
      this.captchaStore.delete(uuid);
      return false;
    }

    // 验证成功后删除验证码
    this.captchaStore.delete(uuid);

    // 不区分大小写比较
    return captcha.text.toLowerCase() === inputText.toLowerCase();
  }

  /**
   * 清理过期验证码
   */
  static cleanExpiredCaptcha(): void {
    const now = Date.now();
    for (const [uuid, captcha] of this.captchaStore.entries()) {
      if (now > captcha.expires) {
        this.captchaStore.delete(uuid);
      }
    }
  }

  /**
   * 生成简单数字验证码（用于非图形环境）
   */
  static generateSimpleCaptcha(length: number = 6): CaptchaResult {
    const chars = '0123456789';
    let text = '';
    for (let i = 0; i < length; i++) {
      text += chars.charAt(Math.floor(Math.random() * chars.length));
    }

    const uuid = randomBytes(16).toString('hex');

    // 存储验证码，5分钟过期
    this.captchaStore.set(uuid, {
      text,
      expires: Date.now() + 5 * 60 * 1000,
    });

    return {
      uuid,
      image: '', // 简单模式下不生成图片
      text,
      captchaEnabled: false,
    };
  }
}
